package com.by.utils;

import io.netty.util.Timeout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 设置redis缓存，并设置过期时间
     *
     * @param key
     * @param value
     * @param timeout 有效期，单位：秒
     */
    public void setEx(String key, Object value, long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    /**
     * key不存在时，保存成功
     *
     * @param key
     * @param value
     */
    public boolean setNx(String key, String value) {
        return redisTemplate.opsForValue().setIfAbsent(key, value);
    }
    /**
     * key不存在时，保存成功
     *
     * @param key
     * @param value
     */
    public boolean setNx(String key, String value, long timeout) {
        return redisTemplate.opsForValue().setIfAbsent(key, value, timeout, TimeUnit.SECONDS);
    }
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }
    public void lpush(String key, String value) {
        redisTemplate.opsForList().leftPush(key, value);
    }
    public void lrange(String key, int start, int end) {
        redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * 设置key的过期时间 单位：秒
     * @param key
     * @param timeout
     */
    public void expire(String key, int timeout) {
        redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }
    public Boolean del(String key){
        return redisTemplate.delete(key);
    }

    public Object hget(String key, String field) {
        return redisTemplate.opsForHash().get(key, field);
    }
    public void hset(String key, String field, Object value) {
        redisTemplate.opsForHash().put(key, field, value);
    }

    /**
     * 返回指定模式所有key
     * @param pattern
     * @return
     */
    public Set<String> keys(String pattern){
        return redisTemplate.keys(pattern);
    }
}
